package com.andaily.web.controller.mobile.thing;

import com.andaily.domain.dto.thing.EventDto;
import com.andaily.domain.dto.thing.EventOverviewDto;
import com.andaily.service.ThingService;
import com.andaily.web.controller.validator.EventDtoValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author Shengzhao Li
 */
@Controller
@RequestMapping("/thing/event")
public class EventController {

    private static Logger logger = LoggerFactory.getLogger(EventController.class);

    @Autowired
    private ThingService thingService;

    private EventDtoValidator eventDtoValidator = new EventDtoValidator();

    @RequestMapping("overview")
    public String overview(EventOverviewDto overviewDto, Model model) {
        overviewDto = thingService.loadEventOverviewDto(overviewDto);
        if (overviewDto.getFullListSize() == 0) {
            logger.debug("Empty created event, redirect to add event form");
            return "redirect:form";
        }
        model.addAttribute("overviewDto", overviewDto);
        return "thing/event_overview";
    }


    @RequestMapping(value = "form", method = RequestMethod.GET)
    public String form(String guid, Model model) {
        EventDto eventDto = thingService.loadEventDto(guid);
        model.addAttribute("eventDto", eventDto);
        return "thing/event_form";
    }

    @RequestMapping(value = "form", method = RequestMethod.POST)
    public String submit(@ModelAttribute("eventDto") EventDto eventDto, BindingResult result) {
        eventDtoValidator.validate(eventDto, result);
        if (result.hasErrors()) {
            return "thing/event_form";
        }
        thingService.persistEventDto(eventDto);
        return "redirect:overview?addEvent=true";
    }

    @RequestMapping("details/{guid}")
    public String details(@PathVariable("guid") String guid, Model model) {
        EventDto eventDto = thingService.loadEventDto(guid);
        model.addAttribute("eventDto", eventDto);
        return "thing/event_details";
    }

    @RequestMapping("delete/{guid}")
    public String delete(@PathVariable("guid") String guid) {
        thingService.deleteEvent(guid);
        return "redirect:../overview";
    }

}
